import type { ProjectConfig, HeaderSetting, MenuSetting, TransitionSetting, MultiTabsSetting } from '/#/config';
import type { BeforeMiniState, SysConfigInfo } from '/#/store';
import variables from '/@/styles/variables.module.scss'
import { defineStore } from 'pinia';
import { store } from '/@/store';
import {theme} from 'ant-design-vue'
import { ThemeEnum } from '/@/enums/appEnum';
import { APP_DARK_MODE_KEY_, PROJ_CFG_KEY } from '/@/enums/cacheEnum';
import { Persistent } from '/@/utils/cache/persistent';
import { darkMode } from '/@/settings/designSetting';
import { resetRouter } from '/@/router';
import { deepMerge } from '/@/utils';
// import { forEach } from '/@/utils/helper/treeHelper';

interface AppState {
  darkMode?: ThemeEnum | string;
  // Page loading status
  pageLoading: boolean;
  // project config
  projectConfig: ProjectConfig | null;
  // When the window shrinks, remember some states, and restore these states when the window is restored
  beforeMiniInfo: BeforeMiniState;
  themeName?: string | null;
  themeConfig: any;
}
let timeId: TimeoutHandle;
export const useAppStore = defineStore({
  id: 'app',
  state: (): AppState => ({
    darkMode: undefined,
    pageLoading: false,
    projectConfig: Persistent.getLocal(PROJ_CFG_KEY),
    beforeMiniInfo: {},
    themeName: undefined,
    themeConfig: {
      token: {
        colorPrimary: '#108ee9',
          // colorSuccess: '#1dc779',
          // colorWarning: '#ffb302',
          // colorError: '#cf4444',
          // colorInfo: '#27ba9b',
          wireframe: true
      },
      algorithm: window.localStorage.getItem('__APP__DARK__MODE__') === 'light' ? theme.defaultAlgorithm : theme.darkAlgorithm
    }
  }),
  getters: {
    getPageLoading(): boolean {
      return this.pageLoading;
    },
    getDarkMode(): 'lightdark' | 'dark' | string {
      return this.darkMode || localStorage.getItem(APP_DARK_MODE_KEY_) || darkMode;
    },
    getThemeName(): string {
      return this.themeName || ''
    },
    getThemeConfig():any { 
      return this.themeConfig
    },
    getBeforeMiniInfo(): BeforeMiniState {
      return this.beforeMiniInfo;
    },
    getProjectConfig(): ProjectConfig {
      return this.projectConfig || ({} as ProjectConfig);
    },
    getHeaderSetting(): HeaderSetting {
      return this.getProjectConfig.headerSetting;
    },
    getMenuSetting(): MenuSetting {
      return this.getProjectConfig.menuSetting;
    },
    getTransitionSetting(): TransitionSetting {
      return this.getProjectConfig.transitionSetting;
    },
    getMultiTabsSetting(): MultiTabsSetting {
      return this.getProjectConfig.multiTabsSetting;
    },
    getSysConfigInfo(): SysConfigInfo {
      return this.getProjectConfig.sysConfigInfo;
    },
  },
  actions: {
    setPageLoading(loading: boolean): void {
      this.pageLoading = loading;
    },
    setDarkMode(mode: string): void {
      this.darkMode = mode;
      localStorage.setItem(APP_DARK_MODE_KEY_, mode);
      this.themeConfig.algorithm = mode === 'light' ? theme.defaultAlgorithm : theme.darkAlgorithm
    },
    setThemeName(themeName: string): void {
      // const arr = variables || []
      // arr.forEach(function (el, index) { 
      //   console.log(el, index)
      // })
      this.themeConfig.token.colorPrimary = themeName
      this.themeName = themeName
    },
    setThemeConfig(themeConfig:any):void { 
      this.themeConfig = themeConfig
    },
    setBeforeMiniInfo(state: BeforeMiniState): void {
      this.beforeMiniInfo = state;
    },
    setProjectConfig(config: DeepPartial<ProjectConfig>): void {
      debugger
      this.projectConfig = deepMerge(this.projectConfig || {}, config as any);
      let keyName = ''
      for (const [key, value] of Object.entries(variables )) {
        console.log(key, value);
        if (value === this.projectConfig?.themeColor) {
          keyName = key
          document.documentElement.setAttribute('data-theme', keyName);
          this.setThemeName(this.projectConfig?.themeColor)
        }
      }
      Persistent.setLocal(PROJ_CFG_KEY, this.projectConfig);
    },
    async resetAllState() {
      resetRouter();
      Persistent.clearAll();
    },
    async setPageLoadingAction(loading: boolean): Promise<void> {
      if (loading) {
        clearTimeout(timeId);
        // Prevent flicker
        timeId = setTimeout(() => {
          this.setPageLoading(loading);
        }, 50);
      } else {
        this.setPageLoading(loading);
        clearTimeout(timeId);
      }
    },
  },
});

// Need to be used outside the setup
export function useAppStoreWithOut() {
  return useAppStore(store);
}